package com.jxauaia.contest.controller;

import com.jxauaia.contest.common.response.Result;
import com.jxauaia.contest.model.dto.ChangePasswordDTO;
import com.jxauaia.contest.model.dto.UserProfileDTO;
import com.jxauaia.contest.model.entity.User;
import com.jxauaia.contest.service.FileService;
import com.jxauaia.contest.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.*;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/user-profile")
public class UserProfileController {

    private static final Logger logger = LoggerFactory.getLogger(UserProfileController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private FileService fileService;

    /**
     * 获取当前用户信息
     */
    @GetMapping("/detail")
    public Result<User> getCurrentUserProfile() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            logger.error("认证对象为空");
            return Result.error(401, "未认证用户");
        }

        logger.debug("认证对象类型: {}", authentication.getClass().getName());
        logger.debug("认证对象详情: {}", authentication);
        logger.debug("认证对象主体: {}", authentication.getPrincipal());

        String username = authentication.getName();
        logger.info("当前认证用户名: {}", username);

        User user = userService.findByUsername(username);

        if (user == null) {
            System.out.println("数据库中未找到用户: " + username);
            return Result.error(404, "用户不存在");
        }

        System.out.println("成功找到用户: " + user.getUsername() + ", ID: " + user.getId());

        // 不返回敏感信息
        user.setPassword(null);
        return Result.success(user);
    }

    /**
     * 获取指定用户的个人主页信息
     */
    @GetMapping("/{userId}")
    public Result<User> getUserProfile(@PathVariable Integer userId) {
        User user = userService.getUserPersonalPage(userId);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }
        // 不返回敏感信息
        user.setPassword(null);
        return Result.success(user);
    }

    /**
     * 更新当前用户信息
     */
    @PutMapping("/update")
    public Result<User> updateCurrentUserProfile(@RequestBody @Validated UserProfileDTO userProfileDTO) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username);

        if (currentUser == null) {
            return Result.error(404, "用户不存在");
        }

        User updatedUser = userService.updateUserProfile(currentUser.getId(), userProfileDTO);
        return Result.success("个人信息更新成功", updatedUser);
    }

    /**
     * 更新指定用户信息（需要权限验证）
     */
    @PutMapping("/{userId}")
    @PreAuthorize("authentication.principal.id == #userId or hasRole('ADMIN')")
    public Result<User> updateUserProfile(
            @PathVariable Integer userId,
            @RequestBody @Validated UserProfileDTO userProfileDTO) {
        User updatedUser = userService.updateUserProfile(userId, userProfileDTO);
        if (updatedUser == null) {
            return Result.error(404, "用户不存在");
        }
        return Result.success("个人信息更新成功", updatedUser);
    }

    /**
     * 上传头像
     */
    @PostMapping("/avatar/upload")
    @PreAuthorize("isAuthenticated()")  // 添加权限验证
    public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User currentUser = userService.findByUsername(username);

            if (currentUser == null) {
                return Result.error(404, "用户不存在");
            }

            // 上传头像文件
            String avatarUrl = fileService.uploadFile(file, "avatars");

            // 更新用户头像
            UserProfileDTO userProfileDTO = new UserProfileDTO();
            userProfileDTO.setAvatar(avatarUrl);
            userService.updateUserProfile(currentUser.getId(), userProfileDTO);

            return Result.success("头像上传成功", avatarUrl);
        } catch (IOException e) {
            return Result.error(500, "头像上传失败: " + e.getMessage());
        }
    }

    /**
     * 修改密码
     */
    @PutMapping("/password/update")
    @PreAuthorize("isAuthenticated()")  // 添加权限验证
    public Result<Boolean> changePassword(@RequestBody @Validated ChangePasswordDTO changePasswordDTO) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username);

        if (currentUser == null) {
            return Result.error(404, "用户不存在");
        }

        boolean success = userService.changePassword(currentUser.getId(), changePasswordDTO);
        return success ? Result.success("密码修改成功", true) : Result.error(400, "密码修改失败");
    }

    /**
     * 注销账号
     */
    @DeleteMapping("/cancel")
    public Result<Boolean> cancelAccount(@RequestBody Map<String, String> passwordMap) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username);

        if (currentUser == null) {
            return Result.error(404, "用户不存在");
        }

        String password = passwordMap.get("password");
        if (password == null || password.isEmpty()) {
            return Result.error(400, "请提供密码以确认注销操作");
        }

        // 修改为deactivateAccount方法
        boolean success = userService.deactivateAccount(currentUser.getId(), currentUser.getId());
        return success ? Result.success("账号已成功注销", true) : Result.error(400, "账号注销失败");
    }

    /**
     * 获取所有可用头像
     */
    @GetMapping("/avatars")
    public Result<List<String>> getAllAvatars() {
        List<String> avatars = fileService.getAllAvatars();
        return Result.success(avatars);
    }
}